<template>
    <view class="container">
        <!-- 顶部标题和操作按钮 -->
        <view class="header">
            <view class="header-left">
                <van-icon name="arrow-left"  @click="goBack" />
                <text class="title">图片管理</text>
            </view>
            <view class="header-actions">
                <text class="action-btn" @click="toggleSelectMode">{{ isSelectMode ? '取消' : '批量删除' }}</text>
                <text v-if="isSelectMode" class="action-btn delete" @click="batchDelete">删除({{ selectedImages.length
                    }})</text>
            </view>
        </view>

        <!-- 主分类标签页 -->
        <scroll-view class="tabs main-tabs" scroll-x :show-scrollbar="false">
            <view v-for="(tab, index) in mainTabs" :key="index" class="tab-item"
                :class="{ active: currentMainTab === index }" @click="switchMainTab(index)">
                <text class="tab-text">{{ tab.name }}</text>
            </view>
        </scroll-view>

        <!-- 子分类标签页 -->
        <scroll-view v-if="showSubTabs" class="tabs sub-tabs" scroll-x :show-scrollbar="false">
            <view v-for="(tab, index) in subTabs" :key="index" class="tab-item"
                :class="{ active: currentSubTab === index }" @click="switchSubTab(index)">
                <text class="tab-text">{{ tab.name }}</text>
            </view>
        </scroll-view>

        <!-- 图片列表 -->
        <scroll-view class="image-list" scroll-y>
            <view class="image-grid">
                <view v-for="(image, index) in currentImages" :key="index" class="image-item"
                    :class="getImageItemClass(image)"
                    @click="handleImageClick(image)">
                    <image :src="image.picUrl" mode="aspectFill" class="image" />
                    <view class="image-info">
                        <!-- <text class="image-title">{{ image.title }}</text> -->
                        <text class="image-time">{{ image.createDate }}</text>
                    </view>
                    <view v-if="isSelectMode" class="select-indicator">
                        <uni-icons :type="selectedImages.includes(image.id) ? 'checkbox-filled' : 'circle'" size="24"
                            color="#007AFF"></uni-icons>
                    </view>
                    <view v-else class="image-actions">
                        <view class="action-btn delete" @click.stop="deleteSingleImage(image)">
                            <uni-icons type="trash" size="16" color="#ffffff"></uni-icons>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>

        <!-- Vant的浮动按钮 -->
        <van-floating-bubble 
            icon="plus" 
            axis="xy" 
            magnetic="x" 
            @click="onBubbleClick"
        />
    </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { showToast, showImagePreview } from 'vant';

const mainTabs = [
    { name: '日照金山', hasSubTabs: true },
    { name: '蓝月谷', hasSubTabs: true },
    { name: '姐妹湖', hasSubTabs: true },
    { name: '大理照片', hasSubTabs: false },
    { name: '昆明照片', hasSubTabs: false },
    { name: '丽江照片', hasSubTabs: false }
];

const subTabs = [
    { name: '横版', type: 0 },
    { name: '竖版', type: 1 }
];

const currentMainTab = ref(0);
const currentSubTab = ref(0);
const images = ref([]);
const isSelectMode = ref(false);
const selectedImages = ref([]);

const onOffsetChange = (offset) => {
    return showToast(`x: ${offset.x.toFixed(0)}, y: ${offset.y.toFixed(0)}`);
};

// 获取当前显示的图片列表
const currentImages = computed(() => {
    return images.value;
});

// 是否显示子标签页
const showSubTabs = computed(() => {
    return mainTabs[currentMainTab.value].hasSubTabs;
});

// 获取当前分类的图片类型
const getCurrentType = computed(() => {
    const mainTab = mainTabs[currentMainTab.value];
    if (!mainTab.hasSubTabs) {
        // 直接返回对应类型的ID
        switch (mainTab.name) {
            case '大理照片': return 101;
            case '昆明照片': return 201;
            case '丽江照片': return 301;
            default: return 0;
        }
    } else {
        // 根据主标签和子标签计算类型ID
        const baseType = mainTab.name === '日照金山' ? 61 :
            mainTab.name === '蓝月谷' ? 71 :
                mainTab.name === '姐妹湖' ? 81 : 0;
        return baseType + currentSubTab.value;
    }
});

// 切换主标签页
const switchMainTab = async (index) => {
    currentMainTab.value = index;
    currentSubTab.value = 0; // 重置子标签页
    await loadImages();
};

// 切换子标签页
const switchSubTab = async (index) => {
    currentSubTab.value = index;
    await loadImages();
};

// 加载图片
const loadImages = async () => {
    try {
        const type = getCurrentType.value;
        // console.log('Loading images for type:', type); // 添加日志
        const response = await request({
            url: '/api/profilepic/GetProfilesAsync?_type=' + type,
            method: 'GET'
        });
        // console.log('API Response:', response); // 添加日志
        if (response.status && Array.isArray(response.data) && response.data.length > 0) {
            images.value = response.data;
        } else {
            images.value = [];
            uni.showToast({
                title: '暂无图片数据',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('加载图片失败:', error);
        images.value = [];
        uni.showToast({
            title: '加载图片失败',
            icon: 'none'
        });
    }
};

// 预览图片
const previewImage = (image) => {
    const urls = images.value.map(item => item.picUrl);
    const currentIndex = images.value.findIndex(item => item.id === image.id);
    showImagePreview({
        images: urls,
        swipeDuration: 50,
        closeable: true,
        loop: true,
        startPosition: currentIndex
    });
};

// 切换选择模式
const toggleSelectMode = () => {
    isSelectMode.value = !isSelectMode.value;
    if (!isSelectMode.value) {
        selectedImages.value = [];
    }
};

// 切换图片选中状态
const toggleSelect = (image) => {
    const index = selectedImages.value.indexOf(image.id);
    if (index === -1) {
        selectedImages.value.push(image.id);
    } else {
        selectedImages.value.splice(index, 1);
    }
};

// 批量删除
const batchDelete = async () => {
    if (selectedImages.value.length === 0) {
        uni.showToast({
            title: '请选择要删除的图片',
            icon: 'none'
        });
        return;
    }

    try {
        const token = uni.getStorageSync('token');
        if (!token) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        await uni.showModal({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedImages.value.length} 张图片吗？`,
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const response = await request({
                            url: '/api/profilepic/DeletePic?ids=' + selectedImages.value.join(','),
                            method: 'GET',
                            headers: {
                                'Authorization': 'Bearer ' + token
                            }
                        });

                        if (response.status === 200) {
                            await loadImages();
                            selectedImages.value = [];
                            isSelectMode.value = false;
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success'
                            });
                        } else {
                            throw new Error('删除失败');
                        }
                    } catch (error) {
                        console.error('删除请求失败:', error);
                        if (error.response && error.response.status === 401) {
                            uni.showToast({
                                title: '登录已过期，请重新登录',
                                icon: 'none'
                            });
                            uni.removeStorageSync('token');
                            uni.removeStorageSync('isLoggedIn');
                            uni.removeStorageSync('username');
                            setTimeout(() => {
                                uni.navigateTo({
                                    url: '/pages/Auth/Login'
                                });
                            }, 1500);
                        } else {
                            uni.showToast({
                                title: '删除失败',
                                icon: 'none'
                            });
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('删除操作失败:', error);
        uni.showToast({
            title: '删除失败',
            icon: 'none'
        });
    }
};

// 单独删除图片
const deleteSingleImage = async (image) => {
    try {
        const token = uni.getStorageSync('token');
        if (!token) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        await uni.showModal({
            title: '确认删除',
            content: '确定要删除这张图片吗？',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const response = await request({
                            url: '/api/profilepic/DeletePic?ids=' + image.id.toString(),
                            method: 'GET',
                            headers: {
                                'Authorization': 'Bearer ' + token
                            }
                        });

                        if (response.status === 200) {
                            await loadImages();
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success'
                            });
                        } else {
                            throw new Error('删除失败');
                        }
                    } catch (error) {
                        console.error('删除请求失败:', error);
                        if (error.response && error.response.status === 401) {
                            uni.showToast({
                                title: '登录已过期，请重新登录',
                                icon: 'none'
                            });
                            uni.removeStorageSync('token');
                            uni.removeStorageSync('isLoggedIn');
                            uni.removeStorageSync('username');
                            setTimeout(() => {
                                uni.navigateTo({
                                    url: '/pages/Auth/Login'
                                });
                            }, 1500);
                        } else {
                            uni.showToast({
                                title: '删除失败',
                                icon: 'none'
                            });
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('删除操作失败:', error);
        uni.showToast({
            title: '删除失败',
            icon: 'none'
        });
    }
};

// 浮动按钮点击事件
const onBubbleClick = () => {
    uni.showActionSheet({
        itemList: ['上传图片', '刷新列表'],
        success: (res) => {
            switch (res.tapIndex) {
                case 0:
                    // 上传图片
                    uni.chooseImage({
                        count: 1,
                        success: async (res) => {
                            try {
                                const token = uni.getStorageSync('token');
                                if (!token) {
                                    uni.showToast({
                                        title: '请先登录',
                                        icon: 'none'
                                    });
                                    return;
                                }

                                const tempFilePath = res.tempFilePaths[0];
                                const type = getCurrentType.value;

                                // 上传图片
                                const uploadRes = await uni.uploadFile({
                                    url: request.defaults.baseURL + '/api/profilepic/UploadPic',
                                    filePath: tempFilePath,
                                    name: 'formFiles',
                                    formData: {
                                        _type: type
                                    },
                                    header: {
                                        'Authorization': 'Bearer ' + token
                                    }
                                });

                                if (uploadRes.statusCode === 200) {
                                    uni.showToast({
                                        title: '上传成功',
                                        icon: 'success'
                                    });
                                    // 刷新图片列表
                                    await loadImages();
                                } else {
                                    throw new Error('上传失败');
                                }
                            } catch (error) {
                                console.error('上传失败:', error);
                                uni.showToast({
                                    title: '上传失败',
                                    icon: 'none'
                                });
                            }
                        }
                    });
                    break;
                case 1:
                    // 刷新列表
                    loadImages();
                    break;
            }
        }
    });
};

// 返回上一页
const goBack = () => {
    const pages = getCurrentPages();
    if (pages.length > 1) {
        uni.navigateBack();
    } else {
        // 如果没有导航历史，则跳转到首页
        uni.switchTab({
            url: '/pages/Home/index'
        });
    }
};

// 页面加载时获取图片
onShow(() => {
    loadImages();
});

// 在 script setup 部分添加新的处理函数
const handleImageClick = (image) => {
    if (isSelectMode.value) {
        toggleSelect(image);
    } else {
        previewImage(image);
    }
};

// 在 script setup 部分添加新的计算属性
const getImageItemClass = (image) => {
    return {
        'selected': isSelectMode.value && selectedImages.value.includes(image.id)
    };
};
</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-top: 120px; // 为固定定位的标签页留出空间
}

.header {
    padding: 20px;
    background-color: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;

    .header-left {
        display: flex;
        align-items: center;
        gap: 10px;

        .back-btn {
            padding: 4px;
            display: flex;
            align-items: center;
            justify-content: center;

            .back-icon {
                font-size: 24px;
                color: #333;
                font-weight: bold;
            }
        }
    }

    .title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
    }

    .header-actions {
        display: flex;
        gap: 15px;

        .action-btn {
            font-size: 14px;
            color: #007AFF;
            padding: 4px 8px;

            &.delete {
                color: #ff4d4f;
            }
        }
    }
}

.tabs {
    background-color: #ffffff;
    white-space: nowrap;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    position: fixed;
    left: 0;
    right: 0;
    z-index: 99;

    &.main-tabs {
        top: 60px; // header高度
    }

    &.sub-tabs {
        top: 110px; // header + main-tabs高度
        background-color: #f8f8f8;
    }

    .tab-item {
        display: inline-block;
        padding: 8px 20px;
        margin: 0 5px;
        border-radius: 20px;

        &.active {
            background-color: #007AFF;

            .tab-text {
                color: #ffffff;
            }
        }

        .tab-text {
            font-size: 14px;
            color: #666;
        }
    }
}

.image-list {
    height: calc(100vh - 120px);
    // padding: 5px;1
    margin-top: 50px;
}

.image-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    padding: 0 5px;
}

.image-item {
    background-color: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    position: relative;
    transition: all 0.3s ease;
    
    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }
    
    &.selected {
        border: 2px solid #007AFF;
    }
    
    .image {
        width: 100%;
        height: 200px;
    }
    
    .image-info {
        padding: 12px;
        
        .image-time {
            font-size: 12px;
            color: #999;
        }
    }

    .select-indicator {
        position: absolute;
        top: 10px;
        right: 10px;
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: 50%;
        padding: 2px;
    }

    .image-actions {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 2;
        opacity: 0;
        transition: opacity 0.3s ease;

        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: rgba(255, 77, 79, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: all 0.2s ease;

            &:active {
                transform: scale(0.95);
                background-color: rgba(255, 77, 79, 1);
            }
        }
    }

    &:hover .image-actions {
        opacity: 1;
    }
}
</style>